#include "ImagePreviewArea.hpp"

ImagePreviewArea::ImagePreviewArea(QWidget *parent)
    : QScrollArea(parent)
{
    // 设置滚动区域属性
    this->setBackgroundRole(QPalette::Light);
    this->setAlignment(Qt::AlignCenter);

    // 初始化用于显示图片的Label
    this->imageLabel = new QLabel{this};
    this->imageLabel->setFrameShape(QFrame::Box);
    this->imageLabel->setBackgroundRole(QPalette::Base);
    this->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    this->imageLabel->setScaledContents(false); // 不自动缩放以保持原始比例
    this->imageLabel->setAlignment(Qt::AlignCenter);

    // 设置QLabel为滚动区域的子部件
    this->setWidget(this->imageLabel);
}

bool ImagePreviewArea::load(const QImage &image)
{
    auto ret = false;
    if (not image.isNull()) {
        this->image = image;
        this->updateDisplay();
        ret = true;
    }
    return ret;
}

bool ImagePreviewArea::load(const QString &filePath)
{
    auto ret      = false;
    auto newImage = QImage{};
    if (newImage.load(filePath)) {
        this->load(newImage);
        ret = true;
    }
    return ret;
}

const QImage &ImagePreviewArea::getOriginalImage() const
{
    return this->image;
}

void ImagePreviewArea::clear()
{
    this->image = QImage{};
    updateDisplay();
}

void ImagePreviewArea::updateDisplay()
{
    if (this->image.isNull()) {
        this->imageLabel->clear();
    }

    auto displayPixmap = QPixmap::fromImage(this->image);
    this->imageLabel->setPixmap(displayPixmap);
    this->imageLabel->resize(displayPixmap.size());
}
